package com.exercise.beginner.adapterview

import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Toast
import com.exercise.beginner.R
import com.exercise.beginner.databinding.ActivityAdapterViewBinding
import com.exercise.structer.BaseActivity
import kotlin.random.Random

class AdapterViewActivity : BaseActivity<ActivityAdapterViewBinding>() {
    private var mAdapter: ArrayAdapter<String>? = null
    private var mRandom: Random? = null

    override val bindingInflater: (LayoutInflater) -> ActivityAdapterViewBinding
        get() = ActivityAdapterViewBinding::inflate

    override fun initView() {
        mAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, generateData())
        binding.listView.run {
            this.adapter = mAdapter
            setOnItemClickListener { _, _, position, _ ->
                val item = mAdapter?.getItem(position) ?: return@setOnItemClickListener
                toast("item: $item")
            }
        }

        binding.addBtn.setOnClickListener {
            val newData = generateData()
            toast("新增${newData.size}个数据!")
            mAdapter?.addAll(newData)
        }

        binding.addHeader.setOnClickListener {
            val footerView = createHeaderView().apply {
                setOnClickListener {
                    toast("click: Header")
                }
            }
            binding.listView.addHeaderView(footerView)
        }
        binding.addFooter.setOnClickListener {
            val footerView = createFooterView().apply {
                setOnClickListener {
                    toast("click: Footer")
                }
            }
            binding.listView.addFooterView(footerView)
        }
    }

    private fun createHeaderView(): View {
        return layoutInflater.inflate(
            R.layout.activity_adapter_view_header,
            binding.listView,
            false
        )
    }
    private fun createFooterView(): View {
        return layoutInflater.inflate(
            R.layout.activity_adapter_view_footer,
            binding.listView,
            false
        ).apply {
            setOnClickListener {
                toast("click: Footer")
            }
        }
    }

    private fun generateData(): List<String> {
        mRandom = Random(System.currentTimeMillis())
        val count = mRandom!!.nextInt(10)
        return (0 until count).map {
            "list item $it"
        }
    }

    private fun toast(msg: String) {
        Toast.makeText(this@AdapterViewActivity, msg, Toast.LENGTH_SHORT).show()
    }
}